<template>
    <div>
        <el-form label-width="80px" :model="spu">
            <el-form-item label="SPU名称">
                <el-input placeholder="spu的名称" v-model="spu.spuName"></el-input>
            </el-form-item>
            <el-form-item label="品牌">
                <el-select placeholder="请选择品牌" v-model="spu.tmId">
                    <el-option :label="tm.tmName" :value="tm.id" v-for="(tm,index) in tradeMarkList" :key="tm.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="SPU描述">
                <el-input type="textarea" rows="4" placeholder="描述" v-model="spu.description"></el-input>
            </el-form-item>
            <!-- //上传图片 -->
            <el-form-item label="SPU图片">
                <el-upload action="dev-api/admin/product/fileUpload" list-type="picture-card"
                    :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handlerSuccess"
                    :file-list="spuImageList">
                    <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
            </el-form-item>
            <el-form-item label="销售属性">
                <el-select :placeholder="`还有${unSelectSaleAttr.length}未选择`" v-model="attrIdAndAttrName">
                    <el-option :label="unselect.name" :value="`${unselect.id}:${unselect.name}`"
                        v-for="(unselect,index) in unSelectSaleAttr" :key="unselect.id">
                    </el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-plus" :disabled="!attrIdAndAttrName" @click="addSaleAttr">添加销售属性
                </el-button>
                <el-table style="width: 100%;" border :data="spu.spuSaleAttrList">
                    <el-table-column label="序号" width=60px align="center" type="index"></el-table-column>
                    <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
                    <el-table-column label="属性值名称列表" prop="prop">
                        <!-- 属性值名称tag -->
                        <template slot-scope="{row,$index}">
                            <el-tag :key="tag.id" v-for="(tag,index) in row.spuSaleAttrValueList" closable
                                :disable-transitions="false" @close="row.spuSaleAttrValueList.splice(index,1)">
                                {{tag.saleAttrValueName}}
                            </el-tag>
                            <!-- 切换事件   -->
                            <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue"
                                ref="saveTagInput" size="small" @blur="handleInputConfirm(row)"
                                @keyup.enter.native="handleInputConfirm(row)">
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="addSaleAttrValue(row)">添加
                                <!-- @click="showInput" -->
                            </el-button>

                        </template>
                    </el-table-column>
                    <el-table-column label="操作" prop="prop">
                        <!-- 删除按钮 -->
                        <template slot-scope="{row,$index}">
                            <el-button type="danger" icon="el-icon-delete" size="mini"
                                @click="spu.spuSaleAttrList.splice($index,1)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="addOrUpdataSpu">保存</el-button>
                <el-button @click="cancel">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
    export default {
        name: 'SpuForm',
        data() {
            return {
                dialogImageUrl: '',
                dialogVisible: false,
                spu:
                {
                    category3Id: 0,
                    description: "",
                    spuImageList: [
                        // {
                        //     "id": 0,
                        //     "imgName": "string",
                        //     "imgUrl": "string",
                        //     "spuId": 0
                        // }
                    ],
                    spuName: "",
                    tmId: '',
                    spuSaleAttrList: [
                        // {
                        //     "baseSaleAttrId": 0,
                        //     "id": 0,
                        //     "saleAttrName": "string",
                        //     "spuId": 0,
                        //     "spuSaleAttrValueList": [
                        //         {
                        //             "baseSaleAttrId": 0,
                        //             "id": 0,
                        //             "isChecked": "string",
                        //             "saleAttrName": "string",
                        //             "saleAttrValueName": "string",
                        //             "spuId": 0
                        //         }
                        //     ]
                        // }
                    ],

                }
                ,//存储SPU属性
                tradeMarkList: [],
                spuImageList: [],
                saleAttrList: [],
                attrIdAndAttrName: '',
            }
        },
        computed: {
            unSelectSaleAttr() {
                let res = this.saleAttrList.filter(item => {
                    return this.spu.spuSaleAttrList.every(item1 => {
                        return item.name != item1.saleAttrName
                    })
                })
                return res
            }
        },
        methods: {
            // 图片移除的回调
            handleRemove(file, fileList) {
                this.spuImageList = fileList
            },
            //图片预览的回调
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;

            },
            // 初始化SPUform数据
            async initSpuData(spu) {
                let res = await this.$API.spu.reqSpu(spu.id)
                if (res.code == 200) {
                    this.spu = res.data
                }
                // 获取品牌信息
                let tradeMark = await this.$API.spu.reqTradeMarkList()
                if (tradeMark.code == 200) {
                    this.tradeMarkList = tradeMark.data
                }
                //获取SPU图片数据
                let spuImageRes = await this.$API.spu.reqSpuImageList(spu.id)
                if (spuImageRes.code == 200) {
                    let listArr = spuImageRes.data
                    listArr.forEach(item => {
                        item.name = item.imgName
                        item.url = item.imgUrl
                    })
                    this.spuImageList = listArr
                }
                //获取平台全部销售属性
                let saleRes = await this.$API.spu.reqBaseSaleAttrList()
                if (saleRes.code == 200) {
                    this.saleAttrList = saleRes.data
                }
            },
            //上传成功的回调
            handlerSuccess(response, file, fileList) {
                this.spuImageList = fileList
            },
            //添加新的销售属性
            addSaleAttr() {
                const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(':')
                let newSaleAttr = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] }
                this.spu.spuSaleAttrList.push(newSaleAttr)
                this.attrIdAndAttrName = ''
            },
            //添加按钮的回调
            addSaleAttrValue(row) {
                this.$set(row, 'inputVisible', true)
                this.$set(row, 'inputValue', '')
            },
            // el-input失去焦点的事件
            handleInputConfirm(row) {
                row.inputVisible = false
                const { baseSaleAttrId, inputValue } = row
                if (inputValue.trim() == '') {
                    this.$message({
                        type: 'error',
                        message: '属性值不能为空'
                    })
                    return
                }
                // 属性去重
                let res = row.spuSaleAttrValueList.some(item => item.saleAttrValueName == inputValue
                )
                if (res) {
                    return
                }

                let newSaleAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue }
                console.log(inputValue);
                row.spuSaleAttrValueList.push(newSaleAttrValue)
            },
            // 保存按钮的回调
            async addOrUpdataSpu() {
                this.spu.spuImageList = this.spuImageList.map(item => {
                    return {
                        imgName: item.name,
                        imgUrl: (item.response && item.response.data) || item.url
                    }
                })
                let res = await this.$API.spu.reqAddOrUpdateSpu(this.spu)

                if (res.code == 200) {
                    this.$message({
                        type: 'success',
                        message: '保存成功'
                    })
                    this.$emit('changeScene', { scene: 0, flag: this.spu.id ? '修改' : '添加' })
                    // 清除数据
                    Object.assign(this._data, this.$options.data())
                }
            },
            // 添加SPU
            async addspuDate(category3Id) {
                this.spu.category3Id = category3Id
                let tradeMark = await this.$API.spu.reqTradeMarkList()
                if (tradeMark.code == 200) {
                    this.tradeMarkList = tradeMark.data
                }
                let saleRes = await this.$API.spu.reqBaseSaleAttrList()
                if (saleRes.code == 200) {
                    this.saleAttrList = saleRes.data
                }
            },
            cancel() {
                this.$emit('changeScene', { scene: 0, flag: '' })
                Object.assign(this._data, this.$options.data())
            }
        },
    }
</script>
<style>
    .el-tag+.el-tag {
        margin-left: 10px;
    }

    .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }

    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
    }
</style>